#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__='Jack Zhang'

'''
JSON API definition.
'''

import json,logging,inspect,functools

# 建立Page类来处理分页,可以在page_size更改每页项目的个数
class Page(object):

    def __init__(self,itemCount,pageIndex=1,pageSize=8):
        self.itemCount=itemCount
        self.pageSize=pageSize
        self.pageCount=itemCount//pageSize+(1 if itemCount%pageSize>0 else 0)
        if (itemCount==0) or (pageIndex>self.pageCount):
            self.offset=0
            self.limit=0
            self.page_index=1
        else:
            self.page_index=pageIndex
            self.offset=self.pageSize*(pageIndex-1)
            self.limit=self.pageSize
        self.has_next=self.page_index<self.pageCount
        self.has_previous=self.page_index>1

    def __str__(self):
        return 'item count: %s, page count: %s, page index: %s, page size: %s, offset: %s, limit: %s'%\
               (self.itemCount,self.pageCount,self.page_index,self.pageSize,self.offset,self.limit)

    __repr__=__str__

class APIError(Exception):
    '''
    the base APIError which contains error(required), data(optional) and message(optional).
    '''
    def __init__(self,error,data='',message=''):
        super(APIError,self).__init__(message)
        self.error=error
        self.data=data
        self.message=message

class APIValueError(APIError):
    '''
    Indicate the input value has error or invalid. The data specifies the error field of input form.
    '''
    def __init__(self,field,message=''):
        super(APIValueError,self).__init__('value:invalid',field,message)

class APIResourceNotFoundError(APIError):
    '''
    Indicate the resource was not found. The data specifies the resource name.
    '''
    def __init__(self,field,message=''):
        super(APIResourceNotFoundError,self).__init__('value:notfound',field,message)

class APIPermissionError(APIError):
    '''
    Indicate the api has no permission.
    '''
    def __init__(self,message=''):
        super(APIPermissionError,self).__init__('permission:forbidden','permission',message)